from flask import Blueprint, request, jsonify
from flask import Blueprint, request, jsonify
from models.entity.organization import Organization
from models.entity.user import User
from models.entity.department import Department
from utils.result import result

import datetime
import json

mod = Blueprint("organization", __name__, url_prefix="/core/organization", template_folder="templates", static_folder="static")

@mod.route("/get_by_organization_id/",methods=["GET", "POST"])
def get_organization_by_id_interface():
    """
    根据机构id获取其信息
    """
    # request: json
    # {
    #       id: id
    # }
    # return: json
    # {
    #       id: id,
    #       name: "name",
    #       code: "code",
    #       description: "description",
    #       parent_id: parent_id,
    #       ParentId: ParentId,
    #       Level: Level,
    #       child_num: child_num,
    #       dis_order: dis_order,
    #       status: status,(0|1 0表示该机构在系统中正常 1表示该机构在系统中被禁用)
    #       chinese_name: "chinese_name",
    #       english_name: "english_name",
    #       set_up_time: "set_up_time",
    #       person_in_charge: "person_in_charge",
    #       email: "email",
    #       fax: "fax",
    #       location: "location",
    #       zip_code: "zip_code",
    #       web: "web",
    #       management_scope: "management_scope",
    #       character: "character"
    # }
    try:
        data = json.loads(bytes.decode(request.data))
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    the_organization = Organization().get_entity_by_id(data["id"])
    if not the_organization:
        return result(success=0, error_code=-3, error_msg="指定机构不存在")
    t_dic = the_organization.to_dict()
    return result(data=[t_dic])


@mod.route("/get_all/",methods=["GET", "POST"])
def get_organization_all_interface():
    """
    获取所有机构
    """
    # return: json
    # [
    #       {
    #           id: id,
    #           name: "name",
    #           code: "code",
    #           description: "description",
    #           ParentId: ParentId,
    #           Level: Level,
    #           path: "path",
    #           child_num: child_num,
    #           dis_order: dis_order,
    #           status: status, (0|1 0表示该机构在系统中正常 1表示该机构在系统中被禁用)
    #           chinese_name: "chinese_name",
    #           english_name: "english_name",
    #           set_up_time: "set_up_time",
    #           person_in_charge: "person_in_charge",
    #           email: "email",
    #           fax: "fax",
    #           location: "location",
    #           zip_code: "zip_code",
    #           web: "web",
    #           management_scope: "management_scope",
    #           character: "character"
    #       }, ...
    # ]
    organization_all_list=Organization().get_list_all()
    tmp_list = [item.to_dict() for item in organization_all_list]
    return result(data=tmp_list)


@mod.route("/get_tree_by_organization_id/",methods=["POST"])
def get_organization_tree_by_id_interface():
    """
    获取特定机构树形结构
    """
    # request: json
    # {
    #       id: id
    # }
    # return: json
    # {
    #       id: id,
    #       name: "name",
    #       code: "code",
    #       description: "description",
    #       dis_order: dis_order,
    #       status: status, (0|1 0表示该机构在系统中正常 1表示该机构在系统中被禁用)
    #       chinese_name: "chinese_name",
    #       english_name: "english_name",
    #       set_up_time: "set_up_time",
    #       person_in_charge: "person_in_charge",
    #       email: "email",
    #       fax: "fax",
    #       location: "location",
    #       zip_code: "zip_code",
    #       web: "web",
    #       management_scope: "management_scope",
    #       character: "character",
    #       children: [
    #                                       {
    #                                               id: id,
    #                                               name: "name",
    #                                               code: "code",
    #                                               description: "description",
    #                                               dis_order: dis_order,
    #                                               status: status, (0|1 0表示该机构在系统中正常 1表示该机构在系统中被禁用)
    #                                               chinese_name: "chinese_name",
    #                                               english_name: "english_name",
    #                                               set_up_time: "set_up_time",
    #                                               person_in_charge: "person_in_charge",
    #                                               email: "email",
    #                                               fax: "fax",
    #                                               location: "location",
    #                                               zip_code: "zip_code",
    #                                               web: "web",
    #                                               management_scope: "management_scope",
    #                                               character: "character",
    #                                               children: [...]
    #                                       }
    #                               ]
    # }
    try:
        data=json.loads(request.data.decode("utf-8"))
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    the_organization=Organization().get_entity_by_id(data["id"])
    if not the_organization:
        return result(success=0, error_code=-3, error_msg="指定机构不存在")
    t_dic = Organization().get_tree_by_pid(the_organization.id)
    return result(data=t_dic)


@mod.route("/get_tree/",methods=["POST"])
def get_organization_tree_all_interface():
    """
    获取所有机构的树形结构
    """
    # return: json
    # [
    #   {
    #       id: id,
    #       name: "name",
    #       code: "code",
    #       description: "description",
    #       dis_order: dis_order,
    #       status: status, (0|1 0表示该机构在系统中正常 1表示该机构在系统中被禁用)
    #       chinese_name: "chinese_name",
    #       english_name: "english_name",
    #       set_up_time: "set_up_time",
    #       person_in_charge: "person_in_charge",
    #       email: "email",
    #       fax: "fax",
    #       location: "location",
    #       zip_code: "zip_code",
    #       web: "web",
    #       management_scope: "management_scope",
    #       character: "character",
    #       children: [
    #                                       {
    #                                               id: id,
    #                                               name: "name",
    #                                               code: "code",
    #                                               description: "description",
    #                                               dis_order: dis_order,
    #                                               status: status, (0|1 0表示该机构在系统中正常 1表示该机构在系统中被禁用)
    #                                               chinese_name: "chinese_name",
    #                                               english_name: "english_name",
    #                                               set_up_time: "set_up_time",
    #                                               person_in_charge: "person_in_charge",
    #                                               email: "email",
    #                                               fax: "fax",
    #                                               location: "location",
    #                                               zip_code: "zip_code",
    #                                               web: "web",
    #                                               management_scope: "management_scope",
    #                                               character: "character",
    #                                               children: [...]
    #                                       }
    #                               ]
    #   }, ...
    # ]
    first_level_organizations=Organization.get_first_level_organizations()
    rlist = []
    for item in first_level_organizations:
        t = item.to_dict()
        t["children"]=item.get_tree_by_pid(item.id)
        rlist.append(t)
    return result(data=rlist)


@mod.route("/add/",methods=["POST"])
def add_organization_interface():
    """
    增加机构
    """
    """
    request: json
    {
              "name": "name",
              "code": "code",
              "description": "description",
              "ParentId": 1,
              "dis_order": 1,
              "status": 1,
              "chinese_name": "chinese_name",
              "english_name": "english_name",
              "set_up_time": "set_up_time",
              "person_in_charge": "person_in_charge",
              "email": "email",
              "phone_number": "phone_number",
              "fax": "fax",
              "location": "location",
              "zip_code": "zip_code",
              "web": "web",
              "management_scope": "management_scope",
              "character": "character"
    }
    """
    new_organization=Organization()
    try:
        data=json.loads(request.data.decode("utf-8"))
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    if "id" in data:
        data.pop("id")
    if "set_up_time" in data:
        # YYYY-MM-DD
        try:
            datetime.datetime.strptime(data["set_up_time"],"%Y-%m-%d")
        except ValueError as e:
            return result(success=0, error_code=-5, error_msg="set_up_time格式错误")
    if not Organization.get_organization_by_name(data["name"]) is None:
        return result(success=0, error_code=-3, error_msg="公司名称已被占用")
    if not Organization.get_organization_by_code(data["code"]) is None:
        return result(success=0, error_code=-4, error_msg="公司编码已被占用")
    try:
        new_organization.from_dict(data)
    except RuntimeError as e:
        return result(success=0, error_code=-7, error_msg=str(e))
    if new_organization.save() is False:
        return result(success=0, error_code=-2, error_msg="保存错误")
    return result(success=1)


@mod.route("/edit/",methods=["POST"])
def edit_organization_by_id_interface():
    """
    编辑指定机构
    """
    """
        request: json
        {
                  "id": 1,
                  "name": "name",
                  "code": "code",
                  "description": "description",
                  "ParentId": 1,
                  "dis_order": 1,
                  "status": 1,
                  "chinese_name": "chinese_name",
                  "english_name": "english_name",
                  "set_up_time": "set_up_time",
                  "person_in_charge": "person_in_charge",
                  "email": "email",
                  "phone_number": "phone_number",
                  "fax": "fax",
                  "location": "location",
                  "zip_code": "zip_code",
                  "web": "web",
                  "management_scope": "management_scope",
                  "character": "character"
        }
        """
    try:
        data = json.loads(request.data.decode("utf-8"))
        print('data', data)
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    the_organization = Organization().get_entity_by_id(data["id"])
    if not the_organization:
        return result(success=0, error_code=-3, error_msg="指定机构不存在")
    if "name" in data:
        if (the_organization.name != data["name"]) and (Organization.get_organization_by_name(data["name"]) is not None):
            return result(success=0, error_code=-4, error_msg="公司名称已存在")
    if "code" in data:
        if (the_organization.code!=data["code"]) and (Organization.get_organization_by_code(data["code"]) is not None):
            return result(success=0, error_code=-4, error_msg="公司编号已存在")
    try:
        the_organization.from_dict(data)
    except RuntimeError as e:
        return result(success=0, error_code=-7, error_msg=str(e))
    if the_organization.save() is False:
        return result(success=0, error_code=-5, error_msg="公司保存错误")
    return result(success=1)


@mod.route("/del/",methods=["POST"])
def delete_organization_by_id_interface():
    """
    根据id删除指定机构
    """
    # request: json
    # {
    #       id: id
    # }
    try:
        data=json.loads(request.data.decode("utf-8"))
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    the_organization=Organization().get_entity_by_id(data["id"])
    if len(User.get_users_by_organization_id(the_organization.id))!=0:
        return result(success=0, error_code=-8, error_msg="该公司下仍然具有用户")
    if not Department.get_department_by_org_id(the_organization.id) is None:
        return result(success=0, error_code=-8, error_msg="该公司下仍然具有部门")
    if the_organization:
        child_num=len(Organization().get_list_by_pid(data["id"]))
        if child_num>0:
            return result(success=0, error_code=-8, error_msg="该公司下仍然具有子公司")
        if the_organization.delete() is False:
            return result(success=0, error_code=-7, error_msg="删除错误")
        else:
            return result(success=1)
    else:
        return result(success=0, error_code=-2, error_msg="该公司不存在")


@mod.route("/search/",methods=["POST"])
def organization_search():
    """
    模糊搜索接口
    """
    # request: json
    # {
    #       "query_word":"query_word"
    # }
    try:
        data = json.loads(request.data.decode("utf-8"))
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    if "query_word" in data:
        query_word=data["query_word"]
    else:
        return result(success=0, error_code=-2, error_msg="数据不完整")
    rdic=Organization.search(query_word)
    return jsonify(rdic)
